//
//  deliveryOrder.m
//  VivaModa
//
//  Created by Sergey on 3/27/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "deliveryOrder.h"
#import "deliveryOrder_cell.h"
#import "commentCell.h"

@interface deliveryOrder ()

@end

@implementation deliveryOrder
@synthesize tableView;
@synthesize emspost_locations_data;
@synthesize connection_get_emspost_locations;
@synthesize connection_customer_data;
@synthesize customer_data;
@synthesize payment_data;
@synthesize connection_get_payment;
@synthesize commentView;
@synthesize commentField;
@synthesize saveCommentBtn;
@synthesize sendReqestBtn;
@synthesize addCommentBtn;

@synthesize user_city;
@synthesize user_coutry;
@synthesize user_name;
@synthesize user_region;
@synthesize user_street_adress;
@synthesize emount;
@synthesize needReload;
@synthesize connection_sendOrder;
@synthesize sendOrderData;
@synthesize type_payments;
UIView *enabledView;
NSMutableArray *array_deliver_text;

NSString*name_city;
NSString*name_zone;
NSString*firstname;
NSString*lastname;
NSString*region;
NSString*street_adress;
NSString*telephone;
NSString*name_country;


NSString *text_comment;
NSString *text_postType;/// text for send

NSString *text_type_payment;/// text for payment
NSString *text_type_payment_db;/// text for payment

NSString *last_text_type_payment;
NSString *last_text_type_payment_db;

NSString *paymentPost;

int parced_id_zone = 0;
int parced_id_country = 0;

int indexSelectedTypePost = 100;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    
    
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    
    array_deliver_text = [[NSMutableArray alloc] initWithCapacity:1];
    [self setNavigationTitle];
    [self addCustomBackButton];
    
    [self.saveCommentBtn setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.saveCommentBtn setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];
    
    [self.sendReqestBtn setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.sendReqestBtn setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];
    
    [self.addCommentBtn setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.addCommentBtn setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];
    
    
    [self.type_payments setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.type_payments setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];

    
    
}



-(void)calculateNalogka{
    NSArray *nalogka_array = [[procent_delivery_of_zone getPriceZone:[NSString stringWithFormat:@"%i",parced_id_zone]] componentsSeparatedByString:@":"];
    
    float statValue = 0;
    float statProcent = 0;
    if ([nalogka_array count]==2) {
        statValue = [[nalogka_array objectAtIndex:0] floatValue];
        statProcent = [[nalogka_array objectAtIndex:1] floatValue];
    }else{
        return;
    }
    
    float sum = statValue + self.emount*statProcent/100;
    
    //float nalogka_procent = [procent_delivery_of_zone getPriceZone:[Singleton sharedMySingleton].user_id_zone]
    
    
    NSString *text_nalogka = [NSString stringWithFormat:@"EMS Почта России наложенным платежом в город: %@ %.0f руб.",self.user_city.text,sum];
    
    [array_deliver_text addObject:text_nalogka];
    
    paymentPost = [NSString stringWithFormat:@"%.0f",sum];

}


-(void)setSPSRdata{
    NSString *text = @"СПСР Экспресс";
    [array_deliver_text addObject:text];
}

-(void)setMoskovData{
    NSString *text1 = @"Бесплатная доставка (только для Москвы!) для заказов свыше: 5000 руб. ";
    NSString *text2 = @"Самовывоз. Покупатель сам забирает свой заказ ";
    [array_deliver_text removeAllObjects];
    [array_deliver_text addObject:text1];
    [array_deliver_text addObject:text2];
    NSLog(@"_________________________________");
    
    if (emount>5000) {
        paymentPost = @"0";
    }else{
        paymentPost = @"550";
    }
    [self.tableView reloadData];
}



-(void)viewWillAppear:(BOOL)animated{
    
    if (needReload) {
        indexSelectedTypePost = 100;
        needReload = NO;
        text_comment = @"";
        
        
        last_text_type_payment = @"";
        last_text_type_payment_db = @"";
        text_type_payment = @"";
        text_type_payment_db = @"";
        [Singleton sharedMySingleton].text_payment = @"";
        [Singleton sharedMySingleton].text_payment_db = @"";
        
        
        [array_deliver_text removeAllObjects];
        
        if ([Singleton sharedMySingleton].user_login==1) {
            [self parseCustomerData];
        }
    }
}


-(void)updateDataOnView{
    
    self.user_name.text = [NSString stringWithFormat:@"%@ %@",firstname, lastname];
    self.user_street_adress.text = street_adress;
    self.user_region.text = name_zone;
    self.user_city.text = name_city;
    self.user_coutry.text = name_country;
    
    
    if (parced_id_country==176) {
        /////// Россия
        
        if (parced_id_zone == 98) {// Москва
            [self setMoskovData];
        }else{
            [self calculateNalogka];
            [self setSPSRdata];
            [self parseEMSLocation];
        }
    }else{
        /////// Остальные страны
        [array_deliver_text removeAllObjects];
        [array_deliver_text addObject:@"EMS Почта России (международное отправление) 1255 руб."];
        paymentPost = @"1255";
        [self.tableView reloadData];
    }
}











- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    int count_section = 1;
    if (([text_comment length]>0)) {
        count_section++;
    }
    if (([text_type_payment length]>0)) {
        count_section++;
    }
    return count_section;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return [array_deliver_text count];
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    if (indexPath.section==1 || indexPath.section ==2) {
        //commentCell
        static NSString *CellIdentifier1 = @"commentCell";
        commentCell *cell1 = nil;
        cell1 = (commentCell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        
        if(!cell1)
        {
            NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"commentCell" owner:nil options:nil];
            for(id currentObject in topLevelObjects)
            {
                if([currentObject isKindOfClass:[commentCell class]])
                {
                    cell1 = (commentCell *)currentObject;
                    break;
                }
            }
        }
        
        
        if (indexPath.section==1 && [text_type_payment length]>0) {
            cell1.comment_text.text = text_type_payment;
            [cell1.comment_text setFont:[UIFont fontWithName:@"Arial" size:17]];
        }else{
            cell1.comment_text.text = text_comment;
        }
        
        
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        UIView *bg_sel = [[UIView alloc] initWithFrame:cell1.bounds];
        bg_sel.backgroundColor = [UIColor clearColor];
        cell1.selectedBackgroundView = bg_sel;
        
        
        return cell1;
        
    }else{
        
        static NSString *CellIdentifier = @"deliveryOrder_cell";
        deliveryOrder_cell *cell = nil;
        cell = (deliveryOrder_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if(!cell)
        {
            NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"deliveryOrder_cell" owner:nil options:nil];
            for(id currentObject in topLevelObjects)
            {
                if([currentObject isKindOfClass:[deliveryOrder_cell class]])
                {
                    cell = (deliveryOrder_cell *)currentObject;
                    break;
                }
            }
        }
        
        cell.text_delivery.text = [array_deliver_text objectAtIndex:indexPath.row];
        if (indexPath.row == indexSelectedTypePost-100) {
            [cell.btn_type_deliver setBackgroundImage:[UIImage imageNamed:@"checked_btn"] forState:UIControlStateNormal];
            text_postType = [array_deliver_text objectAtIndex:indexPath.row];
        }else{
            [cell.btn_type_deliver setBackgroundImage:[UIImage imageNamed:@"un_checked_btn"] forState:UIControlStateNormal];
        }
        
        cell.btn_type_deliver.tag = indexPath.row+100;
        [cell.btn_type_deliver addTarget:self action:@selector(setTypePost:) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        UIView *bg_sel = [[UIView alloc] initWithFrame:cell.bounds];
        bg_sel.backgroundColor = [UIColor clearColor];
        cell.selectedBackgroundView = bg_sel;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==1 && [text_type_payment length]>0) {
        return 40;
    }
    
    if (indexPath.section==1 || indexPath.section==2) {     ///для комментария
        if ([text_comment length]>0) {
            UIFont *cellFont = [UIFont systemFontOfSize:15];
            CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
            
            CGSize labelSize = [text_comment sizeWithFont:cellFont
                                        constrainedToSize:constraintSize
                                            lineBreakMode:UILineBreakModeWordWrap];
            
            return labelSize.height + 20.0f;

        }else{
            return 0;
        }
            }else{
        return 110;
    }
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==1 || section==2) {
        return 80;
    }else{
        return 0;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    // Create label with section title
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 40, 315, 44);
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentCenter;
    
    [label setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:22.0]];
    [label setTextColor:[UIColor colorWithRed:29.0/255.0 green:38.0/255.0 blue:39.0/255.0 alpha:1]];
    
    switch (section) {
        case 0:{
            
             break;}
        case 1:{
            if ([text_type_payment length]>0) {
                label.text = @"Тип оплаты";
            }else{
                label.text = @"Комментарий";
            }
            
            break;}
        case 2:{
            label.text = @"Комментарий";
            break;}
        default:
            break;
    }
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    view.backgroundColor = [UIColor  clearColor];
    [view addSubview:label];
    return view;
}



-(void)setTypePost:(id)sender{
    int oldSelected = indexSelectedTypePost;
    //UIButton *btn = (UIButton*)[self.tableView viewWithTag:[sender tag]];
    //[btn setBackgroundImage:[UIImage imageNamed:@"checked_btn"] forState:UIControlEventTouchDown];
    indexSelectedTypePost = [sender tag];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:oldSelected-100 inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    
    NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:indexSelectedTypePost-100 inSection:0];
    NSArray *indexPaths2 = [[NSArray alloc] initWithObjects:indexPath2, nil];
    
    
    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView reloadRowsAtIndexPaths:indexPaths2 withRowAnimation:UITableViewRowAnimationNone];
}




#pragma mark Dejal activity

- (void)displayActivityView
{
    //[self removeActivityView];
    
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    //[self performSelector:@selector(removeActivityView) withObject:nil afterDelay:3.0];
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark




-(void)parseEMSPaymentFromMoskowTO:(NSString*)to_locate{
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://emspost.ru/api/rest?method=ems.calculate&from=city--moskva&to=%@&weight=0.25",to_locate]];     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    connection_get_payment = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_get_payment) {
        self.payment_data = [NSMutableData data];
    }
}



-(void)parseCustomerData{
    NSString* params = [NSString stringWithFormat:@"id_customer=%i",[Singleton sharedMySingleton].user_id];
    NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/get_user.php"];     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
    
    connection_customer_data = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_customer_data) {
        self.customer_data = [NSMutableData data];
    }
}




-(void)parseEMSLocation{
    NSURL* url = [NSURL URLWithString:@"http://emspost.ru/api/rest?method=ems.get.locations&type=russia&plain=true"];     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    connection_get_emspost_locations = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_get_emspost_locations) {
        self.emspost_locations_data = [NSMutableData data];
    }
}




- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (connection == connection_get_emspost_locations) {
        [emspost_locations_data appendData:data];
    }else{
        if (connection == connection_customer_data) {
            [customer_data appendData:data];
        }else{
            if (connection == connection_get_payment) {
                [payment_data appendData:data];
            }else{
                if (connection == connection_sendOrder) {
                    [sendOrderData appendData:data];
                }
            }
        }
    }
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{
    //NSString *result = [[NSString alloc] initWithData:emspost_locations_data encoding:NSUTF8StringEncoding];
    //NSLog(@"result = %@", result);
    
    
    if (connection == connection_get_emspost_locations) {
        [self parseJSON:emspost_locations_data type:2];
    }else{
        if (connection == connection_customer_data) {
            [self parseJSON:customer_data type:1];
        }else{
            if (connection == connection_get_payment) {
                [self parseJSON:payment_data type:3];
            }else{
                if (connection == connection_sendOrder) {
                    [self parseJSON:sendOrderData type:4];
                }
            }
        }
    }
    
    
    
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data type:(int)type{ // type: 1-all list country from emspost
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:data
                          options:kNilOptions
                          error:&error];
    
    
    
    if (type==2) {
        NSDictionary* data_ems = [json objectForKey:@"rsp"];
        if ([[data_ems objectForKey:@"stat"] isEqualToString:@"ok"]) {
            NSArray *data_zone = [data_ems objectForKey:@"locations"];
            //NSLog(@"data_zone count = %i",[data_zone count]);
           
            NSString *result_parse;
            
            for (int i = 0; i < [data_zone count]; i++) {
                
                //NSLog(@"%@",[@"Московская область" uppercaseString] );
                
                //NSLog(@"%@",[[[data_zone objectAtIndex:i] objectForKey:@"name"] uppercaseString] );
                
                //NSLog(@"name_zone === %@",name_zone);
                                
                NSString *web_name_zone = [[[data_zone objectAtIndex:i] objectForKey:@"name"]uppercaseString];
                
                NSString *user_name_zone = [name_zone uppercaseString];
                NSString *user_name_city = [name_city uppercaseString];
                
                if (([web_name_zone rangeOfString:user_name_zone].location != NSNotFound) || [web_name_zone rangeOfString:user_name_city].location != NSNotFound) {
                    result_parse = [[data_zone objectAtIndex:i] objectForKey:@"value"];
                    if ([web_name_zone rangeOfString:user_name_city].location != NSNotFound){
                        result_parse = [[data_zone objectAtIndex:i] objectForKey:@"value"];
                    }
                } 

            }
            
                        
            
            //NSLog(@"result_parse - %@", result_parse);
            
            if ([result_parse length]>0) {
                [self parseEMSPaymentFromMoskowTO:result_parse];
            }else{
                [self.tableView reloadData];
            }
            
            
        }else{
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Уведомление" message:@"Ошибка синхронизации" delegate:nil cancelButtonTitle:@"Закрыть" otherButtonTitles:nil];
            [alert show];
        }
    }else{
        if (type==1) { /// data user from db
            
            NSString* requestResultAutorization = [json objectForKey:@"success"];
            NSArray * array_location = [json objectForKey:@"message"];

                if ([requestResultAutorization integerValue]==1) {
                    if ([array_location count]>0) {
                        [self getLocationNameFromiD:array_location];
                    }else{
                        [self alertUndefinedCustomerID];
                    }
                }else{
                    [self alertUndefinedCustomerID];
                }

        }else{
            if (type==3) {
                NSDictionary* data_ems = [json objectForKey:@"rsp"];
                if ([[data_ems objectForKey:@"stat"] isEqualToString:@"ok"]) {
                    
                    NSString *payment = [data_ems objectForKey:@"price"];
                    
                    NSString *minDate = [[data_ems objectForKey:@"term"] objectForKey:@"min"];
                    
                    NSString *maxDate = [[data_ems objectForKey:@"term"] objectForKey:@"max"];
                    
                    
                    //NSLog(@"payment %@",payment);
                    //NSLog(@"minDate %@",minDate);
                    //NSLog(@"maxDate %@",maxDate);
                    
                    //[array_deliver_text removeAllObjects];
                    
                    NSString *textEMS = [NSString stringWithFormat:@"EMS Почта России %@-%@ дней %@ руб.",minDate,maxDate,payment];
                    
                    paymentPost = payment;
                    
                    [array_deliver_text addObject:textEMS];
                    
                    [self.tableView reloadData];
                }

            }else{
                if (type==4){/// feedback from sending data order
                    //[json objectForKey:@"message"]
                    NSString* requestResultAutorization = [json objectForKey:@"success"];
                    if ([requestResultAutorization integerValue]==1) {
                        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ваш заказ успешно принят"];
                        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                            [self removeActivityView];
                        }];
                        [alert show];
                        
                        [SQLiteAccess deleteWithSQL:@"DELETE FROM Basket"];
                        [[Singleton sharedMySingleton] setBadge];
                    }else{
                        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка" message:@"Ошибка отправки заказа"];
                        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                            [self removeActivityView];
                        }];
                        [alert show];
                    }

                }
            }
        }
    }
    
    [self removeActivityView];
    
}



-(void)alertUndefinedCustomerID{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка соединения" message:@"Неудалось подключиться к учетной записи. Попробуйте выйти с аккаунта и повторно авторизироваться"];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert show];
    
}




-(void)getLocationNameFromiD:(NSArray*)arrayData{
    
    //NSLog(@"arrayData = %@",arrayData);
    
    if ([arrayData count]>0) {
        name_zone = [[arrayData objectAtIndex:0] objectForKey:@"region"];
        name_city = [[arrayData objectAtIndex:0] objectForKey:@"city"];
        firstname = [[arrayData objectAtIndex:0] objectForKey:@"firstname"];
        lastname = [[arrayData objectAtIndex:0] objectForKey:@"lastname"];
        street_adress = [[arrayData objectAtIndex:0] objectForKey:@"street_adress"];
        telephone = [[arrayData objectAtIndex:0] objectForKey:@"telephone"];
        name_country = [[arrayData objectAtIndex:0] objectForKey:@"countries_name"];
        
        parced_id_zone = [[[arrayData objectAtIndex:0] objectForKey:@"zone_id"] integerValue];
        parced_id_country = [[[arrayData objectAtIndex:0] objectForKey:@"country_id"] integerValue];
        
        [self updateDataOnView];
    }else{
        [self alertUndefinedCustomerID];
    }
}








- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseCategories) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}


-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}

/*

UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];

*/

-(IBAction)openCommentOrder:(id)sender{
    if (!enabledView) {
        enabledView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        UIView *shadowBG = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        shadowBG.backgroundColor = [UIColor blackColor];
        shadowBG.alpha = 0.6;
        commentView.frame = CGRectMake(20, 80, 280, 150);
        [enabledView addSubview:shadowBG];
        [enabledView addSubview:commentView];
    }
    
    
   // commentView.backgroundColor = [UIColor blackColor];
    //commentView.alpha = 0.85;
    
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = commentView.bounds;
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor],(id)[[UIColor blackColor] CGColor], (id)[[UIColor lightGrayColor] CGColor], nil];
    
    gradient.cornerRadius = 10;
    [commentView.layer insertSublayer:gradient atIndex:0];
    
    
    commentView.layer.cornerRadius = 10;
    commentField.layer.cornerRadius = 8;
    
    //CATransition *transition = [CATransition animation];
    //transition.duration = 0.3;
    //transition.type = kCATransitionReveal; //choose your animation
    //[enabledView.layer addAnimation:transition forKey:nil];
    [self.tabBarController.view addSubview:enabledView];
    
    [commentField becomeFirstResponder];
}


-(void)closeCommentView{
   // CATransition *transition = [CATransition animation];
    //transition.duration = 0.3;
    //transition.type = kCATransitionReveal; //choose your animation
    //[enabledView.layer addAnimation:transition forKey:nil];
    [enabledView removeFromSuperview];
    [commentField resignFirstResponder];
    text_comment = commentField.text;
    [self.tableView reloadData];
}




- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    
    
    
    
    if (textView.tag==3) {
        if ([textView.text length]>250) {
            return NO;
        }
        
        if ([text hasSuffix:@"\n"]) {
            //[textView resignFirstResponder];
            [self closeCommentView];
            NSLog(@"Return pressed");
        } else {
            NSLog(@"Other pressed");
        }

    }
    
        return YES;
}



-(IBAction)SaveCommentPress:(id)sender{
    //[commentField resignFirstResponder];
    [self closeCommentView];
}




-(void)setNavigationTitle{
    
    
    UILabel *lblTitle = [[UILabel alloc] init];
    lblTitle.text = @"Оформление заказа";
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor colorWithRed:242.0/255.0 green:240.0/255.0 blue:234.0/255.0 alpha:1];
    
    lblTitle.font = [UIFont fontWithName:@"American Retro" size:27.0];
    [lblTitle sizeToFit];
    
    self.navigationItem.titleView = lblTitle;
}

-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 71, 29)];
    
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 20, 20, 20) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Корзина" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}

-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}



- (IBAction)openPicker:(id)sender {
    
    last_text_type_payment = [Singleton sharedMySingleton].text_payment;
    last_text_type_payment_db = [Singleton sharedMySingleton].text_payment_db;
    
    
	PickerAlertView *pickerAlertView = [[PickerAlertView alloc] initWithTitle:@" " message:@" " delegate:self cancelButtonTitle:@"Отмена" otherButtonTitles:@"Выбрать", nil];
    
    //[pickerAlertView setBackgroundColor:[UIColor redColor]];
    
    
	[pickerAlertView show];
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(PickerAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	
    if (buttonIndex == 0) {
        NSLog(@"cencel");
        text_type_payment = last_text_type_payment;
        text_type_payment_db = last_text_type_payment_db;
    }else{
        text_type_payment = [Singleton sharedMySingleton].text_payment;
        text_type_payment_db = [Singleton sharedMySingleton].text_payment_db;
        NSLog(@"Good");
    }
    
    [self.tableView reloadData];
    
}









-(IBAction)sendOrder:(id)sender{
   // NSLog(@"Send Type post = %@",text_postType);
   // NSLog(@"Send Comment post = %@",text_comment);
    
    
    
   // NSLog(@"text_type_payment = %@",text_type_payment);
   // NSLog(@"text_type_payment_db = %@",text_type_payment_db);
    
    if ([text_comment length]<1) {
        text_comment = @"";
    }
    
    
    if ([text_type_payment length]>0 || [text_type_payment_db length]>0) {
        NSArray *array_orders = [SQLiteAccess selectManyRowsWithSQL:@"SELECT id_product, count FROM Basket"];
        
        NSString *orders = @"";
        
        for (int i = 0; i<[array_orders count]; i++) {
            orders = [NSString  stringWithFormat:@"%@%@:%@;",orders,[[array_orders objectAtIndex:i] objectForKey:@"id_product"],[[array_orders objectAtIndex:i] objectForKey:@"count"]];
        }
        
        NSString *params = [NSString stringWithFormat:@"customer_id=%i&order=%@&comment=%@&delivery=%@&payment_method=%@&delivery_cost=%@",[Singleton sharedMySingleton].user_id,orders,text_comment,text_postType,text_type_payment_db,paymentPost];
        
        
        NSLog(@"params=%@",params);
        
        
        NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/add_order.php"]; // куда отправлять
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
        
        connection_sendOrder = [NSURLConnection connectionWithRequest:request delegate:self];
        [self displayActivityView];
        
        if (connection_sendOrder) {
            self.sendOrderData = [NSMutableData data];
        }

    }else{
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Необходимо заполнить тип оплаты"];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        }];
        [alert addButtonWithTitle:@"Выбрать тип оплаты" block:^{
            [self performSelector:@selector(openPicker:) withObject:nil afterDelay:1.0];
        }];
        [alert show];
    }
    
}

@end
